
from requests.exceptions import RequestException
from lxml import etree
from bs4 import BeautifulSoup
from pyquery import PyQuery
import requests
import time,json

def clear(content):
	bookname=content.replace("\n","")
	bookname=bookname.replace(" ","")
	bookname=bookname.replace("\\","")
	return bookname

def getPage(url):
    '''爬取指定url地址的信息'''
    try:
        #定义请求头信息
        headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36'}
        #执行爬取
        res = requests.get(url,headers=headers)
        #判断并返回结果
        if res.status_code == 200:
            return res.text
        else:
            return None
    except RequestException:
        return None

def parsePage(content):
    '''解析爬取网页中内容，并返回结果'''
    # print(content)
    #========使用BeautifulSoup解析======================
    #初始化，返回BeautifulSoup对象
    soup = BeautifulSoup(content,'lxml')
    #解析网页中<tr class="item">....</tr>信息（一部图书信息）
    items = soup.find_all(name="tr",attrs={"class":"item"})
    #遍历并解析每部图书具体信息
    for item in items:
        if ('inq' in str(item)):
            yield {
                'name': clear(item.find(class_="pl2").a.get_text()),
                'name_other': item.find(name='span').get_text(),
                'author': item.find(name='p', class_='pl').get_text(),
                'rating_nums': item.find(name='span', class_='rating_nums').get_text(),
                'inq': item.find(name='span', class_='inq').get_text(),
            }
        else:
            yield {
                'name': clear(item.find(class_="pl2").a.get_text()),
                'name_other': item.find(name='span').get_text(),
                'author': item.find(name='p', class_='pl').get_text(),
                'rating_nums': item.find(name='span', class_='rating_nums').get_text(),
                'inq': "",
            }

def writeFile(content):
    '''解析爬取网页中内容，并返回结果'''
    with open("./result2.txt",'a',encoding="utf-8") as f:
        f.write(json.dumps(content,ensure_ascii=False)+"\n")

def main(offset):
    '''主程序函数，负责调度执行爬取处理'''
    url = 'https://book.douban.com/top250?start='+str(offset)
    html = getPage(url) #执行爬取
    if html:
        for item in parsePage(html): #执行解析并遍历
            print(item)
            writeFile(item) #执行写操作

#判断当前执行是否为主程序，并遍历调度主函数来爬取信息
if __name__ == '__main__':
    for i in range(10):
        main(offset=i*25)
        time.sleep(1)
